<template lang="pug">
el-dialog(
  v-loading="loading"
  custom-class="material-modal"
  :visible.sync="show"
  top="5vh"
  width="1195px"
  @open="beforeOpen"
  :before-close="close"
  :close-on-click-modal="false"
)
  .modal-title.border-bottom(slot="title") 管理分组
  .modal-content
    .modal-content-title 拖拽分组进行排序
    .space-list
      draggable(:list="spaceList" handle=".icon-move-2" filter=".filter" @update="onUpdate" :move="onMove")
        transition-group(tag="div")
          .space-item(v-for="(item, index) in spaceList" :key="index" :class="item.isSystemSpace ? 'filter' : ''")
            .space-item-name {{item.spaceName}}（{{item.count}}）
            .space-item-ft
              .space-item-sys(v-if="item.isSystemSpace") 系统分组
              .iconfont.icon-edit-1(v-if="!item.isSystemSpace" @click="changeName(item)")
              .iconfont.el-icon-delete(v-if="!item.isSystemSpace" @click="delSpace(item)")
              .iconfont.icon-move-2(v-if="!item.isSystemSpace")
  .modal-footer(slot="footer")
    el-button(size="small" type="primary" @click="confirmGroup") 确定
    el-button(size="small" @click="close") 取消
  el-dialog(
    :visible.sync="showDelDialog"
    append-to-body
    width="400px"
    :before-close="cancel"
  )
    .radio-item
      el-radio(v-model="delType" :label="1") 删除分组，组内所有的图片移到未分组
    .radio-item
      el-radio(v-model="delType" :label="2") 删除分组，同时删除组内所有图片
    .dialog-footer(slot="footer")
      el-button(size="small" type="primary" @click="confirm") 确定
      el-button(size="small" @click="cancel") 取消
</template>

<script>
import draggable from 'vuedraggable'
import { getSourceMaterialSpaceList, postUpdateSpace, postDeleteSpace } from 'api'
export default {
  name: 'spaceGroupModal',
  props: {
    show: Boolean
  },
  data () {
    return {
      loading: false,
      delType: 1,
      spaceList: [],
      showDelDialog: false,
      currentItem: {},
      visible: false,
      delSpaceList: []
    }
  },
  components: {
    draggable
  },
  methods: {
    async getSpaceList () {
      try {
        const { ResultSet } = await this.$axios.post(getSourceMaterialSpaceList, { type: 1 })
        ResultSet.userData.data.forEach(item => {
          item.isChecked = false
        })
        this.spaceList = ResultSet.userData.data
      } catch (err) {
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    delSpace (item) {
      this.showDelDialog = true
      this.currentItem = item
    },
    cancel () {
      this.delType = 1
      this.showDelDialog = false
      this.currentItem = {}
    },
    async confirm () {
      try {
        this.delSpaceList.push({ ...this.currentItem, delType: this.delType })
        let index = this.spaceList.findIndex(item => item.sourceMaterialSpaceId === this.currentItem.sourceMaterialSpaceId)
        if (this.delType === 1) {
          this.spaceList.forEach(item => {
            if (item.spaceName === '未分组') {
              item.count = item.count + this.currentItem.count
            }
          })
        }
        this.spaceList.splice(index, 1)
        this.showDelDialog = false
        this.currentItem = {}
        this.delType = 1
      } catch (err) {
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    onMove (e){ 
      if (e.relatedContext.element.sequence === 1 || e.relatedContext.element.sequence === 2 || e.relatedContext.element.sequence === 3) return false
      return true
    },
    changeName (item) {
      this.$prompt('', '编辑分组名称', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: item.spaceName,
        inputValidator: function (val) {
          if (!val) return '请输入分组名称'
          else if (val.length > 6) return '分组名称不能超过6个字符'
        },
        inputErrorMessage: ''
      }).then(({ value }) => {
        item.spaceName = value
        // this.changeGroup()
      })
    },
    onUpdate (e) {
      // this.changeGroup()
    },
    async changeGroup () {
      try {
        this.loading = true
        let list = this.spaceList.map(item => {
          let row = {
            spaceId: item.sourceMaterialSpaceId
          }
          if (!item.isSystemSpace) row.spaceNewName = item.spaceName
          return row
        })
        let query = {
          delSpaceList: [],
          spaceList: list
        }
        let type1 = {
          delType: 1,
          spaceIds: []
        }
        let type2 = {
          delType: 2,
          spaceIds: []
        }
        this.delSpaceList.forEach(item => {
          if (item.delType === 1) {
            type1.spaceIds.push(item.sourceMaterialSpaceId)
          }
          if (item.delType === 2) {
            type2.spaceIds.push(item.sourceMaterialSpaceId)
          }
        })
        if (type1.spaceIds.length) query.delSpaceList.push(type1)
        if (type2.spaceIds.length) query.delSpaceList.push(type2)
        await this.$axios.post(postUpdateSpace, { ...query })
        this.loading = false
        this.$message.success('修改成功！')
        this.$emit('confirm')
      } catch (err) {
        this.loading = false
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    beforeOpen () {
      this.delSpaceList = []
      this.getSpaceList()
    },
    confirmGroup () {
      this.changeGroup()
    },
    close () {
      this.$emit('close')
    }
  }
}
</script>

<style type="text/css" lang="scss">
.material-modal {
  .el-dialog__header {
    border-bottom: 1px solid #EDEDED;
  }
  .el-dialog__body {
    padding: 0;
  }
  .el-dialog__footer {
    padding-bottom: 10px;
    border-top: 1px solid #DCDFE6;
  }
}
</style>

<style lang="scss" scoped>
.modal-content {
  padding: 0 20px;
}
.modal-content-title {
  padding: 15px 0;
  font-size: 14px;
  color: #999;
  line-height: 28px;
}
.space-item {
  padding: 18px 12px 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #DCDFE6;
  .space-item-name {
    font-size: 14px;
    line-height: 28px;
    color: #363636;
  }
}
.space-item-ft {
  display: flex;
  align-items: center;
  .space-item-sys {
    font-size: 14px;
    color: #000;
  }
  .iconfont {
    margin-left: 10px;
    font-size: 16px;
    color: #999;
    &.icon-move-2 {
      cursor: move;
    }
  }
}
.space-list {
  max-height: 600px;
  overflow-y: auto;
}
.radio-item {
  padding: 5px 0;
}
.dialog-footer {
  text-align: center;
}
.modal-footer {
  text-align: center;
  padding: 10px 0;
}
</style>